package com.example.jianbing.juc;

import com.sun.corba.se.impl.resolver.FileResolverImpl;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName : SaleTicket
 * @Description :
 * @Author : JB
 * @Date: 2020-08-03 22:17
 */

class Ticket{
    private int  number = 30;

    /**
     * synchronized
     * */
    /*
    public  synchronized  void saleTicket(){
        if(number > 0){
            System.out.println(Thread.currentThread().getName()+"\t卖出第："+(number--)+"\t还剩下："+number);
        }
    }*/

    private Lock lock = new ReentrantLock();

    /**
     * ReentrantLock
     * */
    public void saleTicket(){
        lock.lock();
        try {
            if(number > 0){
                System.out.println(Thread.currentThread().getName()+"\t卖出第："+(number--)+"\t还剩下："+number);
            }
        } finally {
            lock.unlock();
        }
    }
}

/**
 * 1. 题目 三个售票员  卖出   30张票
 *   多线程编程 的企业级套路+模板
 *   1. 在高内聚低耦合的前提下，线程    操作（对外暴露的方法）  资源类
 */
public class SaleTicket {
    public static void main(String[] args) {

        Ticket ticket = new Ticket();

        new Thread(()->{for (int i = 0; i < 40; i++) ticket.saleTicket();},"A").start();
        new Thread(()->{for (int i = 0; i < 40; i++) ticket.saleTicket();},"B").start();
        new Thread(()->{for (int i = 0; i < 40; i++) ticket.saleTicket();},"C").start();



        /*new Thread(new Runnable() {  //匿名内部类
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.saleTicket();
                }
            }
        },"A").start(); //start()是进入就绪状态，何时执行取决去操作系统调度

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.saleTicket();
                }
            }
        },"B").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.saleTicket();
                }
            }
        },"C").start();*/


    }
}
